import requests, json, time
import argparse, subprocess
from typing import Union
from pathlib import Path
from datetime import datetime, timedelta
from werkzeug.utils import secure_filename

headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
}


def parse_yymmdd(s: str) -> datetime:
    # "250930" → 2025-09-30
    year = 2000 + int(s[:2])
    month = int(s[2:4])
    day = int(s[4:6])
    return datetime(year, month, day)


def format_yymmdd(date: datetime) -> str:
    yy = str(date.year)[-2:]
    mm = f"{date.month:02d}"
    dd = f"{date.day:02d}"
    return f"{yy}-{mm}-{dd}"


def create_repo(name):
    payload = {
        "name": name,
        "description": name,
        "path": name,
        "has_issues": True,
        "has_wiki": True,
        "can_comment": True,
        "auto_init": True,
        "license_template": "GNU_General_Public_License_v3.0",
        "private": False,
        "default_branch": "main",
        "repository_type": "code",
    }

    try:
        response = requests.post(
            "https://api.gitcode.com/api/v5/orgs/source-code/repos?access_token=WX1X-x8R4t65je-x3o6JpMoq",
            headers=headers,
            data=json.dumps(payload),
            allow_redirects=True,
        )
        print(f"Created repo for {name}:", response.text)
    except Exception as e:
        print(f"Error on {name}:", e)


def create_repos_loop():
    date = parse_yymmdd("250101")

    for i in range(1000000000):
        date_str = format_yymmdd(date)

        payload = {
            "name": date_str,
            "description": date_str,
            "path": date_str,
            "has_issues": True,
            "has_wiki": True,
            "can_comment": True,
            "auto_init": True,
            "license_template": "GNU_General_Public_License_v3.0",
            "private": False,
            "default_branch": "main",
            "repository_type": "code",
        }

        try:
            response = requests.post(
                "https://api.gitcode.com/api/v5/orgs/source-code/repos?access_token=WX1X-x8R4t65je-x3o6JpMoq",
                headers=headers,
                data=json.dumps(payload),
                allow_redirects=True,
            )
            print(f"Created repo for {date_str}:", response.text)
        except Exception as e:
            print(f"Error on {date_str}:", e)

        date += timedelta(days=1)

        # 如果需要等待 65 秒，可以取消注释
        # print("等待 65 秒...")
        # time.sleep(65)


def act_git(root_dir: Union[str, Path] = "."):
    root = Path(root_dir)
    # `rglob('*')` will recursively traverse all files and directories.
    for filepath in root.rglob("*"):
        if filepath.is_file():
            if ".git" in filepath.parts:
                continue
            # Relative path (relative to root_dir)
            relpath = filepath.relative_to(root)
            try:
                print(f"Adding: {relpath} in {root}")
                # git add <filepath>
                subprocess.run(["git", "add", str(relpath)], cwd=root, check=True)
                # git commit -m 'Add: <path to file>'
                subprocess.run(
                    ["git", "commit", "-m", f"Add: {relpath}"], cwd=root, check=True
                )
                print(f"Committed: {relpath}")
            except subprocess.CalledProcessError as e:
                print(f"Failed to commit {relpath}: {e}")


parser = argparse.ArgumentParser(
    description="Auto git add & commit files under a directory"
)
parser.add_argument(
    "--dir",
    "-d",
    nargs="?",
    default=".",
    help="Root directory (default: current directory)",
)
parser.add_argument(
    "--prefix",
    "-p",
    nargs="?",
    default="",
    help="Repo prefix (default: empty string)",
)
args = parser.parse_args()
root_dir, prefix = Path(args.dir), args.prefix

for dirpath in root_dir.glob("*"):
    if not dirpath.is_file():
        repo_name = secure_filename(f"{prefix}-{dirpath.name}")
        create_repo(repo_name)
        # time.sleep(10)
        subprocess.run(
            ["pwsh", "-c", "rm", "-Recurse", "-Force", "./.git"],
            cwd=dirpath,
            check=False,
        )
        subprocess.run(["git", "init"], cwd=dirpath, check=True)
        subprocess.run(
            [
                "git",
                "remote",
                "add",
                "origin",
                f"git@gitcode.com:source-code/{repo_name}.git",
            ],
            cwd=dirpath,
            check=True,
        )
        act_git(dirpath)
        subprocess.run(
            ["git", "push", "-u", "origin", "main", "--force"], cwd=dirpath, check=True
        )
        print(f"END upload {repo_name}")
